import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../../atoms/getuser';
import { tbfdmenu, tbfdrolemenu, tbfduserrole } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/menu/my.api');

export type Result = ITbfdmenu[];

export type Message = void;

/**
 * 当前登录用户菜单
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		const user = await getuser(req);
		if (!user) {
			logger.debug('请登录后操作');
			res.status(200).json([]);
			return;
		}
		const role = await tbfduserrole()
			.first('roleid')
			.where({
				userid: user.userid
			});
		if (!role) {
			logger.debug('无法获取角色');
			res.status(200).json([]);
			return;
		}

		const rolemenus = await tbfdrolemenu()
			.select('menuid')
			.where({
				roleid: role.roleid
			});
		const ids = rolemenus.map((it) => {
			return it.menuid;
		});
		const menus = await tbfdmenu()
			.select('*')
			.whereIn('menuid', ids)
			.orderBy('pid', 'asc')
			.orderBy('weight', 'asc');

		res.status(200).json(menus);
	} catch (error) {
		logger.trace(error);
		res.status(200).json([]);
	}
});

export const config = {} as PageConfig;

export default handler;
